import json

from django.db.models import Count, QuerySet
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from ad_manage.models import Advertisement
from django.forms.models import model_to_dict
from django.views.decorators.csrf import csrf_exempt
from adlist.models import SouhuModel, ToutiaoModel, ToutiaoPatameter, SinaPatameter, SouhuPatameter, FenghuangPatameter, \
    RadarPatameter
from ad_manage.controller import advertisement_date_controller
from ad_manage.models import Advertisement, RandomData
from django.utils.timezone import now, timedelta
import requests as req
from PIL import Image
from io import BytesIO
from ad_manage.controller import tag_like_controller
from utils.request_decorator import request_validate
from users.models import UserProfile
# Create your views here.
@request_validate
@csrf_exempt
def advertisement_details(request):         # 详情页加载数据 #
    id = int(request.GET.get('id'))
    advertisement = Advertisement.objects.filter(id=id)
    response = req.get(advertisement[0].img)
    image = Image.open(BytesIO(response.content))   # 获取图片尺寸 #
    advertisements = {'json_data': [model_to_dict(item) for item in advertisement]}
    advertisements['img_size'] = str(image.size[0]) + "*" + str(image.size[1])
    return JsonResponse(advertisements)

@request_validate
@csrf_exempt
def advertisement_industry(request):        # 首页加载所有行业列表 #
    ad_ind_list = Advertisement.objects.annotate(total_num=Count('id')).exclude(industry='暂无').exclude(
        industry='其他').values_list('industry', 'total_num')
    ad_ind_list.query.group_by = ['industry']

    return JsonResponse({'json_data': [item for item in ad_ind_list]})




@csrf_exempt
def advertisement_date(request):
    start = request.GET.get('start')
    end = request.GET.get('end')
    id = int(request.GET.get('id'))
    advertisement = Advertisement.objects.filter(id=id)
    date_list = advertisement_date_controller(advertisement[0], start, end)
    return JsonResponse({"json_data": date_list})



# 详情页下方表格里随机数据的获取 #
def advertisement_random_data(request):
    today = now().date() + timedelta(days=0)
    randomData = RandomData.objects.filter(create_time__gte=str(today))
    return JsonResponse({'json_data': [model_to_dict(item) for item in randomData]})


def get_all_appname(request):
    query = Advertisement.objects.exclude(local_img='暂无').values('app_name').distinct().exclude(app_name='界面')
    return JsonResponse({'json_data': list(query)}, safe=False)


def purchase_page(request):
    return render(request, 'html/main/set_meal.html', None)


def product_introduction(request):
    return render(request, 'html/main/product_introduction.html', None)


# 一次性执行，获取全部图片尺寸  #
def get_all_size(request):
    advertisements = Advertisement.objects.exclude(local_img='暂无').exclude(local_img='')
    for advertisement in advertisements:

        try:
            response = req.get(
                "http://imagethinking.semyes.cn/images/" + str(advertisement.app_id) + "/" + advertisement.local_img)
            image = Image.open(BytesIO(response.content))
            advertisement.image_size = str(image.size[0]) + "*" + str(image.size[1])
            advertisement.save()
        except Exception as e:
            print("http://imagethinking.semyes.cn/images/" + str(
                advertisement.app_id) + "/" + "/" + advertisement.local_img)
            print(e)
    return JsonResponse({'json_data': 'success'})


def image_like(request):
    id = int(request.GET.get('id'))
    advertisement = Advertisement.objects.filter(id=id)
    ad_dict = tag_like_controller(advertisement)
    return JsonResponse({'json_data': ad_dict})

def host_like(request):
    id = int(request.GET.get('id'))
    advertisement = Advertisement.objects.filter(id=id)
    arr = advertisement[0].url.split('/')
    like_url = arr[0]+'//'+arr[2]
    print(like_url)
    return JsonResponse({'json_data': "success"})

def konwledge_page(request):
    return render(request, 'html/main/ueditor/index.html', None)

def check_vip(request):
    id = int(request.GET.get('id'))
    user = UserProfile.objects.filter(id=id)[0]
    dic = {}
    dic['user_level'] = user.vip
    return JsonResponse(dic)
